package com.cangchu.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class GsonUtil {

	private static Gson gson = new Gson();

	public static <T> String toJson(T t) {
		if (t != null)
			return gson.toJson(t);
		else
			return null;
	}

	public static <T> T toEntity(String json, Class<T> clazz) {
		return gson.fromJson(json, clazz);
	}

	public static <T> List<T> toListEntity(String json, Class<T> clazz) {
		return gson.fromJson(json,
				new com.google.gson.reflect.TypeToken<List<T>>() {
				}.getType());
	}

	public static <T> T toEntity(String json, TypeToken<T> typeToken) {
		return gson.fromJson(json, typeToken.getType());
	}

	public final static Gson createGson() {
		if (gson == null) {
			gson = new Gson();
		}
		return gson;
	}

}
